<?php
/**
 * Created by PhpStorm.
 * User: mr.lee
 * Date: 2018/6/6
 * Time: 上午11:29
 *
 */

namespace app\api\controller;


use Alipay\Alipayobj;
use app\common\model\Agent;
use app\common\model\CardGeneral;
use app\common\model\LoginUsers;
use app\common\model\Merchant;
use app\common\model\Paylog;
use app\common\model\Tklog;
use app\common\model\WxOpen;
use think\response\Json;
use Wechat\Wxobjopen;
use Weixinpay\Wxtk;

class Order extends Pub
{


    public function create_order($param)
    {
        $out_trade_no = $this->getorderid($param['merchantid']);
        $data['mid'] = $param['merchantid'];
        $data['orderid'] = $out_trade_no;
        $data['source'] = $param['source'];
        $data['pay_fs'] = $param['channel'];
        $data['d_cashier'] = $param['device_id'];
        $data['kuantai'] = $param['kuantai'];
        $data['price'] = $param['total_fee'];
        $data['yf_price'] = $param['total_fee'];
        $data['pay_cate'] = $param['pay_cate'];
        $data['add_time'] = time();
        $Paylog = new Paylog();
        $add = $Paylog->save($data);
        $infos = ['out_trade_no' => $out_trade_no];
        if ($add) {
            $rarr['return_code'] = "SUCCESS";
            $rarr['return_msg'] = '';
            $rarr['result_code'] = 'SUCCESS';
            $rarr['result_msg'] = '';
            $rarr['info'] = $infos;
        } else {
            $rarr['return_code'] = "SUCCESS";
            $rarr['return_msg'] = '';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '订单号获取失败,请尝试重新发起支付';
        }

        return $rarr;
    }

    //订单详情
    public function orderinfo($param)
    {
        try {
//            $check = $this->checkcashier($param);    //核实收银员
//            if ($check == 0) {
            $Paylog = new Paylog();
            $map['orderid'] = $param['out_trade_no'];
            $map['mid'] = $param['merchantid'];
            $info = $Paylog->where($map)->find();
            if ($info) {
                $infos['trade_no'] = $info['trade_no'];
                $infos['out_trade_no'] = $info['orderid'];
                $infos['total_fee'] = $info['price'];//支付方式
                $infos['channel'] = $info['pay_fs'];//支付方式中文
                $infos['channel_ch']=getpayfs($info['pay_fs']);
                $infos['ought_fee'] = $info['yf_price'];//应付金额
                $infos['gel_fee'] = $info['zk_price'];//折扣金额
                $infos['dis_card_zk'] = $info['dis_card_zk'];        //会员卡折扣     field('dis_card_zk,vip_card_zk,gel_card_zk,hx_card')->
                $infos['vip_card_zk'] = $info['vip_card_zk'];        //等级折扣
                $infos['gel_card_zk'] = $info['gel_card_zk'];        //卡券抵扣
                $infos['service_charge'] = $info['service_charge'];        //卡券抵扣
                $infos['end_time'] = !empty($info['pay_time']) ? $info['pay_time'] : "";//支付时间
                $infos['gel_info'] = getdeduzkinfo($info['hx_card'], $info['gel_card_zk']);        //抵扣明细
                $infos['is_vip'] = "";        //是否会员
                $infos['is_fans'] = "";        //是否会员
                $infos['card_name'] = "";        //会员姓名
                $infos['card_num'] = $info['card_num'];        //会员卡号
                $infos['refund_fee'] = $info['tk_price'];        //退款金额
                $infos['pay_statu'] = getpaystatus($info['pay_statu']);        //支付状态
                $infos['cashier'] = $info['cashier']?$info['cashier']:$info['d_cashier']; ;        //收银员
                $infos['remark'] = $info['remark'];        //备注
                $Tklog = new Tklog();
                $tklist = [];
                $tkinfo = $Tklog->where(array('pid' => $info['id'], 'tk_status' => 1))->field('tk_orderid,tk_fs,action_user,refund_fee,addtime')->select();
                foreach ($tkinfo as $k => $v) {
                    $tklist[$k]['refund_orderid'] = $v['tk_orderid'];
                    $tklist[$k]['refund_source'] = $v['tk_fs'];
                    $tklist[$k]['refund_user'] = $v['action_user'];
                    $tklist[$k]['refund_fee'] = $v['refund_fee'];
                    $tklist[$k]['refund_time'] = $v['addtime'];
                }
                $infos['refund_list'] = $tklist;
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '';
                $rarr['result_code'] = 'SUCCESS';
                $rarr['result_msg'] = '';
                $rarr['info'] = _unsetNull($infos);
            } else {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '';
                $rarr['result_code'] = 'FAIL';
                $rarr['result_msg'] = '订单查询失败';
            }
//            } else {
//                $rarr['return_code'] = "SUCCESS";
//                $rarr['return_msg'] = '';
//                $rarr['result_code'] = 'FAIL';
//                $rarr['result_msg'] = '您无权限查询该订单';
//            }
        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = '系统错误';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '系统错误' . $e->getMessage();
        }
        return $rarr;
    }

    public function getorderprice($param)
    {
        try {

            $map['mid'] = $param['merchantid'];
            $User = new Merchant();
            $shtd = $User->where('id', $param['merchantid'])->value('shtd');
            if ($shtd == 0) {
                $map['orderid'] = $param['out_trade_no'];
            } elseif ($shtd == 1) {
                $map['ms_orderid'] = $param['out_trade_no'];
            } elseif ($shtd == 10) {
                $map['trade_no'] = $param['out_trade_no'];
            } else {
                $map['orderid'] = $param['out_trade_no'];
            }
            $Paylog = new Paylog();
            $order = $Paylog->where($map)->find();
//        $addtime=;
            $Tklog = new Tklog();
            $map2['tk_status'] = 1;
            $map2['orderid'] = $order['orderid'];
            $ytk = $Tklog->where($map2)->sum('refund_fee');
            if ($order) {
                $arr = array('out_trade_no' => $order['orderid'],
                    'channel' => $order['pay_fs'],
                    'total_fee' => $order['price'],
                    'refund_fee' => $ytk,
                    't_orderid' => $order['orderid'],
                    'orderno' => $order['orderno'],
                    'device_id' => !empty($order['cashier']) ? $order['cashier'] : $order['d_cashier'],
                    'end_time' => date('Y-m-d H:i:s', $order['add_time']),
                    'openid' => $order['openid']);
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '';
                $rarr['result_code'] = 'SUCCESS';
                $rarr['result_msg'] = '获取成功';
                $rarr['info'] = $arr;
            } else {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '';
                $rarr['result_code'] = 'FAIL';
                $rarr['result_msg'] = '订单编号不存在';
            }
        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = '系统错误';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '系统错误' . $e->getMessage();
        }
        return $rarr;


    }

    public function getorderrefund($param)
    {

        try {

//            $rarr['return_code'] = "SUCCESS";
//            $rarr['return_msg'] = '您没有退款权限';
//            $rarr['result_code'] = 'FAIL';
//            $rarr['result_msg'] = "您没有退款权限";
//            return $rarr;

            $map['orderid|trade_no'] = $param['out_trade_no'];
            $map['mid'] = $param['merchantid'];
            $Paylog = new Paylog();
            $payinfo = $Paylog->where($map)->find();

            if ($payinfo) {
                $pay_way = $payinfo['pay_way'];
                $pay_fs = $payinfo['pay_fs'];
                $pay_cate = $payinfo['pay_cate'];
                if ($pay_cate == "wx_deposit") {
                    $DepositOrder = new DepositOrder();
                    $rarr = $DepositOrder->wxorderrefund($param);
                } else {
                    $User = new Merchant();
                    $shtd = $User->where(array('id' => $param['merchantid']))->value('shtd');
                    switch ($shtd) {
                        case '0':
                            $OfficalOrder = new OfficialOrder();
                            $rarr = $OfficalOrder->getorderrefund($param, $pay_fs);
                            break;
                        case '1':
                            $rarr = $this->msrefund($param);
                            break;
                        case '2':
                            $NotCardOrder = new NotCardOrder();
                            $rarr = $NotCardOrder->getorderrefund($param, $pay_fs);
                            break;
                        case "10":
                            $LftOrder = new LftOrder();
                            $rarr = $LftOrder->orderrefund($param);
                            break;
                    }
                }
            } else {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '订单编号不存在';
                $rarr['result_code'] = 'FAIL';
                $rarr['result_msg'] = "订单编号不存在";
            }
        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = '系统错误';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '系统错误' . $e->getMessage();
        }
        return $rarr;
    }

    public function order_refund_query($param)
    {
        try {
            $map['orderid|trade_no'] = $param['out_trade_no'];
            $map['mid'] = $param['merchantid'];
            $map['pay_statu'] = array('neq', 0);
            $Paylog = new Paylog();
            $payinfo = $Paylog->where($map)->find();

            if ($payinfo) {
                $pay_way = $payinfo['pay_way'];
                $pay_fs = $payinfo['pay_fs'];
                $pay_cate = $payinfo['pay_cate'];
                if ($pay_cate == "wx_deposit") {
                    $DepositOrder = new DepositOrder();
                    $rarr = $DepositOrder->wx_order_refund_query($param);
                } else {
                    switch ($pay_way) {
                        case '0':

                            $OfficalOrder = new OfficialOrder();
                            $rarr = $OfficalOrder->order_refund_query($param, $pay_fs);
                            break;
                        case "2":
                            $NotCardOrder = new NotCardOrder();
                            $rarr = $NotCardOrder->order_refund_query($param, $pay_fs);
                            break;
                        case "10":
                            $LftOrder = new LftOrder();
                            $rarr = $LftOrder->order_refund_query($param, $payinfo['mid']);
                            break;
                    }
                }
            } else {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '订单编号不存在';
                $rarr['result_code'] = 'FAIL';
                $rarr['result_msg'] = "订单编号不存在";
            }

        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = '系统错误';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '系统错误' . $e->getMessage();
        }
        return $rarr;
    }

    public function getorderreverse($param)
    {
        try {
            $map['orderid|trade_no'] = $param['out_trade_no'];
            $map['mid'] = $param['merchantid'];
            $Paylog = new Paylog();
            $payinfo = $Paylog->where($map)->find();

            if ($payinfo) {
                $pay_way = $payinfo['pay_way'];
                $pay_fs = $payinfo['pay_fs'];
                $pay_cate = $payinfo['pay_cate'];
                if ($pay_cate == "wx_deposit") {
                    $DepositOrder = new DepositOrder();
                    $rarr = $DepositOrder->wxreverse($param);
                } else {
                    switch ($pay_way) {
                        case '0':
                            $OfficalOrder = new OfficialOrder();
                            $rarr = $OfficalOrder->getorderreverse($param, $pay_fs);
                            break;
                        case "1":
                            $rarr = $this->msreverse($param);
                            break;
                        case "2":
                            $NotCardOrder = new NotCardOrder();
                            $rarr = $NotCardOrder->getorderreverse($param, $pay_fs);
                            break;
                        case "10":
                            $LftOrder = new LftOrder();
                            $rarr = $LftOrder->orderreverse($param);
                            break;
                    }
                }
            } else {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '订单编号不存在';
                $rarr['result_code'] = 'FAIL';
                $rarr['result_msg'] = "订单编号不存在";
            }
        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = "系统错误" . $e->getMessage();
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = "系统错误" . $e->getMessage();
        }
        return $rarr;
    }

    public function create_wx_order($param)
    {
        $out_trade_no = $this->getorderid($param['merchantid']);;
        $sub_openid = $param['sub_openid'];
        $data['orderid'] = $out_trade_no;
        $data['mid'] = $param['merchantid'];
//            $data['openid'] = request()->post('openid');
        $data['openid'] = $param['sub_openid'];
        $data['pay_statu'] = 0;
        $data['add_time'] = time();
        $data['attach'] = $param['attach'];;
        if (isset($param['trade_no'])) {
            $data['trade_no'] = $param['trade_no'];;
        }
        $Paylog = new Paylog();
        $Paylog->save($data);

        $Merchant = new Merchant();
        $Agent = new Agent();
        $WxOpen = new WxOpen();
        $map['id'] = $param['merchantid'];
        $config = $Merchant->where($map)->find();


        $agent = $Agent->where(array('id' => $config['agent']))->find();
        $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();

        $userwx = $WxOpen->where(array('id' => $config['wx_open_id']))->find();
        $options = array(
            'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
            'partnerid' => $agent['partnerid'], // 财付通商户身份标识
            'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
        );
        $weObj = new Wxobjopen($options);

        $yf_price = $param['total_fee'];
//        $zkarr['merchantid'] = $param['merchantid'];
//        $zkarr['openid'] = $param['sub_openid'];
//        $zkarr['total_fee'] = $yf_price;
//        $zkarr['orderid'] =$out_trade_no;;

        $zk_price = 0;

        $pay_fees = $yf_price - $zk_price;

        $data2['price'] = $pay_fees;

        $Paylog->save($data2, ['orderid' => $out_trade_no]);

        $appid = $users['authorizer_appid'];
        $mch_id = $agent['partnerid'];

        $body = "快捷支付";
        $sub_mch_id = $config['sub_mch_id'];
        $sub_appid = $userwx['authorizer_appid'];
        $total_fee = $pay_fees * 100;

//            $openid = request()->post('openid');
        $notify_url = 'https://os.wunengkeji.com/api.php';
        $spbill_create_ip = $_SERVER["REMOTE_ADDR"];

        $nonce_str = $weObj->generateNonceStr();
        $param_data['appid'] = $appid;
        if ($config['wechat_way'] == 0) {
            $param_data['sub_appid'] = $sub_appid;
            $param_data['sub_openid'] = $sub_openid;
            $openid = "";

        } else {
            $openid = $sub_openid;

        }
        $param_data['mch_id'] = $mch_id;
        $param_data['sub_mch_id'] = $sub_mch_id;
        $param_data['nonce_str'] = $nonce_str;
        $param_data['body'] = $body;
        $param_data['out_trade_no'] = $out_trade_no;
        $param_data['total_fee'] = $total_fee;
        $param_data['spbill_create_ip'] = $spbill_create_ip;
        $param_data['notify_url'] = $notify_url;
        $param_data['openid'] = $openid;
        $param_data['attach'] = $param['attach'];
        $param_data['trade_type'] = "JSAPI";
        $param_data['receipt'] = $config['efp_receipt'];
        $param_data['profit_sharing'] = $config['is_profit'];
        file_put_contents('/data2/html/osapi/aa111.log', json_encode($param_data), 8);

        $pay_xml = $weObj->createWxPackageXml($param_data);
//        $pay_xml = $weObj->createPackageXml2($appid, $sub_appid, $mch_id, $sub_mch_id, $nonce_str, $body, $out_trade_no, $total_fee, $spbill_create_ip, $notify_url, $openid, $sub_openid);
        $pay_xml = $weObj->get_pay_id($pay_xml);
        file_put_contents('/data2/html/osapi/aa111.log', json_encode($pay_xml), 8);

        if ($pay_xml['return_code'] == "SUCCESS") {
            if ($pay_xml['result_code'] == "SUCCESS") {
                $prepay_id = $pay_xml['prepay_id'];
                $jsApiObj["appId"] = $appid;
                $timeStamp = time();
                $jsApiObj["timeStamp"] = "$timeStamp";
                $jsApiObj["nonceStr"] = $nonce_str;
                $jsApiObj["package"] = "prepay_id=" . $prepay_id;
                $jsApiObj["signType"] = "MD5";
                $jsApiObj["paySign"] = $weObj->getPaySignature($jsApiObj);
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '';
                $rarr['result_code'] = 'SUCCESS';
                $rarr['result_msg'] = '';
                $rarr['out_trade_no'] = $out_trade_no;
                $rarr['info'] = $jsApiObj;
            } else {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '';
                $rarr['result_code'] = 'FAIL';
                $rarr['result_msg'] = $pay_xml['err_code_des'];
            }
        } else {
            $rarr['return_code'] = "SUCCESS";
            $rarr['return_msg'] = '';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = $pay_xml['return_msg'];
        }

        return $rarr;
    }


}